<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card" :body-style="{padding: '30px 150px'}">
        <TreeTools :tree-node="company" :is-root="true" @handle-command="handleCommand" />
        <el-tree
          :data="departs"
          default-expand-all
          :expand-on-click-node="false"
        >
          <TreeTools slot-scope="{ data }" :tree-node="data" @handle-command="handleCommand" />
        </el-tree>
      </el-card>
      <Additem v-if="dialogVisible" :id="id" :dialog-visible.sync="dialogVisible" :type="type" @update="getDepartments" />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/treeTools'
import { getDepartments, removeDepartment } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
import Additem from './components/Additem'
export default {
  components: { TreeTools, Additem },
  data() {
    return {
      departs: [],
      defaultProps: {
        label: 'name'
      },
      company: {},
      dialogVisible: false,
      type: '',
      id: ''
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const result = await getDepartments()
      this.company = { id: '', name: result.companyName,
        manager: result.companyManage }
      this.departs = tranListToTreeData(result.depts, '')
    },
    handleCommand(command, id) {
      this.id = id
      if (command === 'add') {
        this.dialogVisible = true
        this.type = '新增部门'
      } else if (command === 'set') {
        this.dialogVisible = true
        this.type = '编辑部门'
      } else {
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            await removeDepartment(id)
            await this.getDepartments()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } catch (error) {
            this.$message({
              type: 'info',
              message: '删除失败'
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
}
</script>

<style>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.flex{
  display: flex;
  justify-content: space-around;
  align-content: center;
}
</style>
